package com.maotai.llzhou.thread;

import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.http.client.config.RequestConfig;

import Decoder.BASE64Encoder;

import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.MaotaiString;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.util.HttpClientUtilNew;
import com.maotai.llzhou.util.IPFactory;
import com.maotai.llzhou.util.JSUtil;

/**
 * 登录并且将商品加入到购物车
 */
public class MaotaiYuYueLoginThread512 extends Thread {

	@Resource(name = "maotaiService")
	private MaotaiService maotaiService;
	private Map<String, Object> zhanghao;

	public MaotaiYuYueLoginThread512(MaotaiService maotaiService,
			Map<String, Object> zhanghao) {
		this.maotaiService = maotaiService;
		this.zhanghao = zhanghao;
	}

	public MaotaiService getMaotaiService() {
		return maotaiService;
	}

	public void setMaotaiService(MaotaiService maotaiService) {
		this.maotaiService = maotaiService;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	@Override
	public void run() {
		MaotaiWebCookie mwc = new MaotaiWebCookie();
		HttpClientUtilNew hcu = HttpClientUtilNew.getInstance();
		try {
			RequestConfig requestConfig = IPFactory.getKdRequestConfigNoProxy();
			String kcross = zhanghao.get("kcross")+"";
			String acw_tc = zhanghao.get("acw_tc")+"";
			String csrfToken = zhanghao.get("csrfToken")+"";
			String uuid = zhanghao.get("uuid")+"";
			mwc.setKcross(kcross);
			mwc.setAcw_tc(acw_tc);
			mwc.setCsrfToken(csrfToken);
			String timestamp = System.currentTimeMillis()+"";
//			String sign = JSUtil.excuFunctionA(mwc.getAuth()+timestamp);
//			mwc.setSign(sign);
//			mwc.setTimestamp(timestamp);
//			String timestamp = System.currentTimeMillis()+"";
//			String sign = JSUtil.excuFunctionA(mwc.getAuth()+timestamp);
//			mwc.setSign(sign);
//			mwc.setTimestamp(timestamp);
			if(uuid==null||"".equals(uuid)||"null".equals(uuid)
					||kcross==null||"".equals(kcross)||"null".equals(kcross)){
				ScriptEngineManager manager = new ScriptEngineManager();
				ScriptEngine engine = manager.getEngineByName("javascript");
				engine.eval("function UUID(){var e=function(){for(var e=1*new Date,t=0;e==1*new Date;){t++}return e.toString(16)+t.toString(16);},t=function(){return Math.random().toString(16).replace(\".\",\"\");},r=function(e){function t(e,t){var r,n=0;for(r=0;r<t.length;r++){n|=i[r]<<8*r}return e^n}var r,n,a={},i=[],o=0;for(r=0;r<a.length;r++){n=a.charCodeAt(r),i.unshift(255&n),i.length>=4&&(o=t(o,i),i=[])}return i.length>0&&(o=t(o,i)),o.toString(16);};var n=String(1920*1080);n=n&&/d{5,}/.test(n)?n.toString(16):String(31242*Math.random()).replace(\".\",\"\").slice(0,8);var a=e()+\"-\"+t()+\"-\"+r()+\"-\"+n+\"-\"+e();return a?(just_test_distinctid_2=1,a):(just_test_distinctid_2=2,(String(Math.random())+String(Math.random())+String(Math.random())).slice(2,15));}");
				Invocable invoke = (Invocable)engine;    // 调用merge方法，并传入两个参数    
				uuid = (String)invoke.invokeFunction("UUID");
		        String cross = "{\"distinct_id\":\""+uuid+"\",\"$device_id\":\""+uuid+"\",\"props\":{\"$latest_traffic_source_type\":\"直接流量\",\"$latest_referrer\":\"\",\"$latest_referrer_host\":\"\",\"$latest_search_keyword\":\"未取到值(直接打开)\"},\"first_id\":\""+uuid+"\"}";
//		        System.out.println(cross);
		        kcross = URLEncoder.encode(cross,"utf-8");
		        mwc.setKcross(kcross);
			}
			//访问茅台主页得到cookie里面的两个值acw_tc,csrfToken
			if(acw_tc==null||"".equals(acw_tc)||"null".equals(acw_tc)){
		        
		        //访问茅台主页，得到两个cookie值
		        mwc = hcu.sendHttpGetProxyIndex("https://www.emaotai.cn/", mwc, requestConfig, "");
		        if(mwc.getAcw_tc()==null ||"".equals(mwc.getAcw_tc())||"null".equals(mwc.getAcw_tc())){
		        	zhanghao.put("loginstatus", "0");
					maotaiService.updateZhanghaoLoginStatus(zhanghao);
					return;
		        }
		        
			}
			
			//装载登录报文
			Map<String, String> maps = new HashMap<String, String>();
			//userCode=nickboowen&userPassword=MTk4NjA2MTg&loginType=name&loginSource=2&loginFlag=1
			maps.put("userCode", zhanghao.get("code")+"");
			maps.put("userPassword", zhanghao.get("pwd")+"");
			maps.put("loginType", "name");
			maps.put("loginSource", "2");
			maps.put("loginFlag", "1");
			//loginSource=2&loginType=name&userCode=13372007847&userPassword=cTE5ODYwNjE4 手机端
			String referer = "https://www.emaotai.cn/smartsales-b2c-web-pc/login";
			
			//登录
			mwc = hcu.sendHttpPostLoginProxy(MaotaiString.LOGIN_URL_NEW,
					mwc, maps, requestConfig,referer);
			System.out.println(zhanghao.get("code")+"--登录"+mwc.getContent());
			
			if(mwc.getContent().contains("未激活")||mwc.getContent().contains("不存在")||mwc.getContent().contains("密码错误")){
				zhanghao.put("loginstatus", "7");
				maotaiService.updateZhanghaoLoginStatus(zhanghao);
				return;
			}
			String auth = mwc.getAuth();
			System.out.println(zhanghao.get("code") + "----" + auth);
			
			// 得到登录之后的标志
			if (mwc.getAuth() != null && !"".equals(mwc.getAuth())) {
				zhanghao.put("auth",auth);
				maotaiService.updateZhanghaoAuth(zhanghao);
				
				//登录后获取用户id，补齐kcross，用于接下来的请求
				if(zhanghao.get("memberId")==null||"".equals(zhanghao.get("memberId"))||"null".equals(zhanghao.get("memberId"))){
					mwc = hcu.sendHttpGetProxy(MaotaiString.GET_MEMBERID_URL_NEW,
							mwc, requestConfig,referer);
					System.out.println(zhanghao.get("code")+"--获取到的用户信息"+mwc.getContent());
					//{"data":{"code":null,"createPerson":"migration program","createTime":"2017-11-14 22:00:09","dr":0,"email":"nickboowen@qq.com","hishopUserId":1765107,"id":3586409,"lockStatus":null,"mobile":"13372007847","orderBy":null,"orderByDesc":null,"password":"","passwordFormat":1,"remark":null,"salt":"","sqlFilters":null,"status":1,"tenantId":1,"updatePerson":"migration program","updateTime":"2018-06-27 08:54:55","userName":"nickboowen","vshopUserId":null},"resultCode":0,"resultMsg":"success"}
					if(mwc==null || mwc.getContent()==null||mwc.getContent().contains("login")){
						zhanghao.put("loginstatus", "0");
						maotaiService.updateZhanghaoLoginStatus(zhanghao);
						return;
					}
					if (mwc.getContent() != null && !"".equals(mwc.getContent())) {
						JSONObject jObject2 = JSONObject.parseObject(mwc
								.getContent());
						JSONObject data = jObject2.getJSONObject("data");
						String memberId = data.getString("id");
						String phone = data.getString("mobile");
						zhanghao.put("memberId", memberId);
						zhanghao.put("phone", phone);
						zhanghao.put("sign", JSUtil.excuFunctionA("EMAOTAI_"+memberId));
						maotaiService.updateZhanghaoMemberId(zhanghao);
						
					}
				}
				if(mwc.getCsrfToken()==null || "".equals(mwc.getCsrfToken())||"null".equals(mwc.getCsrfToken())
						||uuid==null || "".equals(uuid)||"null".equals(uuid)){
					System.out.println(zhanghao.get("code")+" : throws login exception ");
					zhanghao.put("loginstatus", "0");
					maotaiService.updateZhanghaoLoginStatus(zhanghao);
					return;
				}
				//add by llzhou at 2018-08-03
		        String cross = "{\"distinct_id\":\""+zhanghao.get("memberId")+"\",\"$device_id\":\""+uuid+"\",\"props\":{\"$latest_traffic_source_type\":\"直接流量\",\"$latest_referrer\":\"\",\"$latest_referrer_host\":\"\",\"$latest_search_keyword\":\"未取到值(直接打开)\"},\"first_id\":\""+uuid+"\"}";
		        System.out.println(cross);
		        mwc.setKcross(URLEncoder.encode(cross,"utf-8"));
		        zhanghao.put("kcross", URLEncoder.encode(cross,"utf-8"));
		        zhanghao.put("acw_tc", mwc.getAcw_tc());
		        zhanghao.put("csrfToken", mwc.getCsrfToken());
		        zhanghao.put("uuid", uuid);
		        maotaiService.insertZhanghaoCookie(zhanghao);
		        //add by llzhou at 2018-08-03
		        //增加一个登录后提交日志
		        //{\"distinct_id\":\"2200254\",\"lib\":{\"$lib\":\"js\",\"$lib_method\":\"code\",\"$lib_version\":\"1.8.10\"},\"properties\":{\"$screen_height\":1080,\"$screen_width\":1920,\"$lib\":\"js\",\"$lib_version\":\"1.8.10\",\"$latest_traffic_source_type\":\"直接流量\",\"$latest_referrer\":\"\",\"$latest_referrer_host\":\"\",\"$latest_search_keyword\":\"未取到值(直接打开)\",\"$device_id\":\"1653134f424e3-09ee3058123816-454f032b-2073600-1653134f425186\",\"channel\":\"\",\"time\":1534130137527,\"platform\":\"PC端商城\",\"version\":\"v0.7.8\",\"$is_first_day\":true},\"type\":\"track\",\"event\":\"ViewHomePage\",\"time\":1534130137679,\"_nocache\":\"086063680281730\"}
//		        String loginData = "{\"distinct_id\":\""+zhanghao.get("memberId")+"\",\"lib\":{\"$lib\":\"js\",\"$lib_method\":\"code\",\"$lib_version\":\"1.8.10\"},\"properties\":{\"$screen_height\":1080,\"$screen_width\":1920,\"$lib\":\"js\",\"$lib_version\":\"1.8.10\",\"$latest_traffic_source_type\":\"直接流量\",\"$latest_referrer\":\"\",\"$latest_referrer_host\":\"\",\"$latest_search_keyword\":\"未取到值(直接打开)\",\"$device_id\":\""+uuid+"\",\"channel\":\"\",\"time\":"+System.currentTimeMillis()+",\"platform\":\"PC端商城\",\"version\":\"v0.7.8\",\"$is_first_day\":true},\"type\":\"track\",\"event\":\"ViewHomePage\",\"time\":"+(System.currentTimeMillis()+5)+",\"_nocache\":\""+JSUtil.getNocache()+"\"}";
//		        String loginData64 = JSUtil.base64(loginData);
//		        String crc = "crc="+JSUtil.excuHashCode(loginData64);
//		        String dataUrl = "https://i.emaotai.cn/logate/data?data="+URLEncoder.encode(loginData64)+"&ext="+URLEncoder.encode(crc);
//		        System.out.println(dataUrl);
//		        referer = "https://www.emaotai.cn/smartsales-b2c-web-pc/";
//		        hcu.sendHttpGetDataProxy(dataUrl, mwc, requestConfig, referer);
//		        //跳转到主页面
//		        hcu.sendHttpGetProxyIndex(MaotaiString.INDEX_URL, mwc, requestConfig, "https://www.emaotai.cn/smartsales-b2c-web-pc/login");
//		        //并上传主页面的日志
//		         loginData = "{\"distinct_id\":\""+zhanghao.get("memberId")+"\",\"lib\":{\"$lib\":\"js\",\"$lib_method\":\"code\",\"$lib_version\":\"1.8.10\"},\"properties\":{\"$screen_height\":1080,\"$screen_width\":1920,\"$lib\":\"js\",\"$lib_version\":\"1.8.10\",\"$latest_traffic_source_type\":\"\",\"$latest_referrer\":\"\",\"$latest_referrer_host\":\"www.emaotai.cn\",\"$latest_search_keyword\":\"\",\"$device_id\":\""+uuid+"\",\"$referrer\":\"https://www.emaotai.cn/smartsales-b2c-web-pc/\",\"$referrer_host\":\"www.emaotai.cn\",\"$url\":\"https://www.emaotai.cn/smartsales-b2c-web-pc/login\",\"$url_path\":\"/smartsales-b2c-web-pc/login\",\"$title\":\"茅台商城\",\"page_type\":\"UserLogin\",\"args\":\"{}\",\"time\":"+System.currentTimeMillis()+",\"platform\":\"PC端商城\",\"version\":\"v0.7.8\",\"user_id\":\""+zhanghao.get("memberId")+"\",\"freq_user_id\":\""+zhanghao.get("memberId")+"\",\"member_id\":\""+zhanghao.get("memberId")+"\",\"cookie_id\":\""+zhanghao.get("memberId")+"\",\"$os\":\"Windows\",\"$os_version\":\"7\",\"$browser\":\"Chrome\",\"$browser_version\":\"63.0.3239.108\",\"user_agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36\",\"view_dur\":"+JSUtil.getView_dur()+",\"algorithm_id\":\"\",\"$is_first_day\":true,\"$is_first_time\":false},\"type\":\"track\",\"event\":\"$pageview\",\"time\":"+(System.currentTimeMillis()+5)+",\"_nocache\":\""+JSUtil.getNocache()+"\"}";
//		         loginData64 = JSUtil.base64(loginData);
//		         crc = "crc="+JSUtil.excuHashCode(loginData64);
//		         dataUrl = "https://i.emaotai.cn/logate/data?data="+URLEncoder.encode(loginData64)+"&ext="+URLEncoder.encode(crc);
//		        System.out.println(dataUrl);
//		        hcu.sendHttpGetDataProxy(dataUrl, mwc, requestConfig, "https://www.emaotai.cn/");
		        
			}else{
				zhanghao.put("loginstatus", "0");
				maotaiService.updateZhanghaoLoginStatus(zhanghao);
			}
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(zhanghao.get("code")+e.getMessage()+" : throws login exception ");
			try {
				zhanghao.put("loginstatus", "0");
				maotaiService.updateZhanghaoLoginStatus(zhanghao);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
	}
}
